﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using IridiumDB.Repository;
using IridiumFlares;
using IridiumDB.Model;
using IridiumParser;

namespace IridiumDB.Services
{
    public class DatabaseService
    {
        private LocationRepository _repLocation;
        private FlareRepository _repFlare;

        public LocationRepository LocationRepository { get { return _repLocation; } }
        public FlareRepository FlareEntryRepository { get { return _repFlare; } }

        public DatabaseService()
        {
            _repLocation = new LocationRepository();
            _repFlare = new FlareRepository();
        }

        public int SaveFlares(Flare[] flares, Location location)
        {
            Flare tempFlare = null;
            for (int i = 0; i < flares.Length; i++)
            {
                tempFlare = flares[i];
                tempFlare.Location_Ref = location.ID;
                _repFlare.Create(tempFlare);
            }
            return flares.Length;
        }

        public int AddNewFlares(Flare[] flares, Location location, out List<Flare> nonUniqueFlares)
        {
            List<Flare> uniqueFlares = new List<Flare>();
            foreach (var flare in flares)
            {
                if (!_repFlare.Exists(flare))
                    uniqueFlares.Add(flare);
            }

            nonUniqueFlares = flares.Except(uniqueFlares).ToList();

            return SaveFlares(uniqueFlares.ToArray(), location);
        }

        public int UpdateFlares(Flare[] flares, Location location)
        {
            int count = 0;
            var allFlares = _repFlare.FindAllUpcomingForLocationId(location.ID);
            foreach (var flare in allFlares)
            {
                foreach (var newFlare in flares)
                {
                    if (_repFlare.IsUpdate(flare, newFlare))
                    {
                        _repFlare.Update(flare);
                        count++;
                    }
                }
                
            }
            return count;
        }

        public int AddNewLocations(Location[] locations)
        {
            int counter = 0;
            foreach (var location in locations)
            {
                if (!_repLocation.Exists(location))
                {
                    _repLocation.Create(location);
                    counter++;
                }
            }
            return counter;
        }

        public bool AddNewLocation(Location location)
        {
            if (!_repLocation.Exists(location))
            {
                _repLocation.Create(location);
                return true;
            }
            return false;
        }
    }
}
